import os
from random import Random
import uuid
from django.http import HttpResponse
from django.utils import simplejson
from django.conf import settings
import twitter
import urllib2, urllib
import string
import gdata.oauth
import gdata.contacts.data
import gdata.contacts.client
from PIL import Image
import logging
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO
import GeoIP
import pytz


log = logging.getLogger('minutes')

TWITTER_MAX_LENGTH = getattr(settings, 'TWITTER_MAX_LENGTH', 140)

GEOIP = GeoIP.open(os.path.join(settings.GEOIP_PATH, 'GeoLiteCity.dat'),
                   GeoIP.GEOIP_MEMORY_CACHE)
ELITE_RANDOM_AIRTIME = (16,56)


class TwitterError(Exception):
    """Twitter error"""
    pass

def get_country_with_ip(ip):
    record = GEOIP.record_by_addr(ip)
    if record and isinstance(record, dict):
        return record.get('country_code')


def get_timezone_with_ip(ip):
    try:
        record = GEOIP.record_by_addr(ip)
        if record and isinstance(record, dict):
            return record.get('time_zone')
    except Exception as err:
        log.error("Cannot get location: %s" % err)


def convert_timezone(objects, field, user, ip):
    """Convert timezone for each field in objects list"""
    timezone =  getattr(user, 'timezone', None) or get_timezone_with_ip(ip)
    if not timezone:
        return
    for obj in objects:
        date = getattr(obj, field, None)
        if date:
            try:
                new_date = (date.replace(tzinfo=pytz.timezone(getattr(settings, 'TIME_ZONE', 'UTC'))).
                            astimezone(pytz.timezone(timezone)))
                setattr(obj, field, new_date)
            except Exception:
                pass


def post_to_twitter(msg, access_token, access_token_secret):
    """Post to twitter wall"""

    if len(msg) > TWITTER_MAX_LENGTH:
        size = len(msg + '...') - TWITTER_MAX_LENGTH
        msg = u'%s...' % mesg[:-size]
    try:
        twitter_api = twitter.Api(
            consumer_key=settings.TWITTER_CONSUMER_KEY,
            consumer_secret=settings.TWITTER_CONSUMER_SECRET,
            access_token_key=access_token,
            access_token_secret=access_token_secret
            )
        twitter_api.PostUpdate(msg)
    except Exception as err:
        log.error('Twitter posting error: %s' % err)
        raise TwitterError(err)

def get_twitter_avatar(user_id):
    """Get twitter avatar"""
    try:
        twitter_api = twitter.Api()
        user = twitter_api.GetUser(user_id)
        return user.profile_image_url
    except urllib2.HTTPError as err:
        log.error('ERROR: %s' % err)
        return False


def facebook_interests(request):
    try:
        return ', '.join( item['name'] for item in request.graph.me.interests()['data'] )
    except Exception as err:
        log.error('Cannot get %s interests: %s' % (request.user, err))
        return

def ajax_login_required(view_func):
    def wrap(request, *args, **kwargs):
        if request.user.is_authenticated():
            return view_func(request, *args, **kwargs)
        json = simplejson.dumps({'error': 'not_authenticated'})
        return HttpResponse(json, mimetype='application/json')
    wrap.__doc__ = view_func.__doc__
    wrap.__dict__ = view_func.__dict__
    return wrap

def resize_picture(filename, size, filename_to=None):
    try:
        image = Image.open(filename)
        if image.mode != "RGB":
            image = image.convert("RGB")
        image.thumbnail(size, Image.ANTIALIAS)
        image.save(filename_to or filename, settings.IMAGE_FORMAT, quality=85)
        return True
    except Exception as err:
        log.error('Cannot resize image %s: %s' % (filename, err))


def random_number(n):
    return ''.join(str(i) for i in Random().sample(xrange(10), n))


def random_string(n):
    return ''.join(Random().sample(string.ascii_letters+string.digits, n))


def elite_random_airtime():
    return Random().randint(*ELITE_RANDOM_AIRTIME)


def make_upload_path(instance=None, filename=None):
    """Generates upload path for ImageField"""
    while True:
        upload_file = u"%s%s" % (uuid.uuid4().get_hex(), '.jpg')
        if not os.path.exists(os.path.join(settings.MEDIA_ROOT, upload_file)):
            return upload_file


def resize_save_file(filename, content, size):
    try:
        with open(filename, 'wb+') as destination:
            new = StringIO()
            if not resize_picture(StringIO(content), size, new):
                return False
            new.seek(0)
            destination.write(new.read())
            return True
    except Exception as err:
        log.error(err)
        return False

def get_search_cookie(request, value, default):
    try:
        return int(request.COOKIES.get(value, default))
    except (ValueError, TypeError):
        return default

def get_int(value, default):
    try:
        return int(value)
    except (ValueError, TypeError):
        return default

def get_live_key(search, chapter='8live'):
    search = search.copy()
    if search.get('created_by__in', ''): return
    search.pop('slumped', '')
    search.pop('created__gte', '')
    search.pop('time_expired__lte', '')
    return '%s_%s' % (chapter, '_'.join([ '%s:%s' % key for key in sorted(search.items()) ]))


def get_feeds(feed):
    """ Parse contact feed """
    contacts = {}
    for entry in feed.entry:
        for email in entry.email:
            if email.primary and email.primary == 'true':
                contacts.update({email.address: entry.title.text})
    return contacts


def get_google_contacts(token, token_secret):
    """Google contacts"""
    token, token_secret = urllib.unquote(token.encode('ascii')), \
                          urllib.unquote(token_secret.encode('ascii'))
    client = gdata.contacts.client.ContactsClient()
    client.auth_token = gdata.gauth.OAuthHmacToken(settings.GOOGLE_CONSUMER_KEY,
                                                   settings.GOOGLE_CONSUMER_SECRET,
                                                   token, token_secret,
                                                   gdata.gauth.ACCESS_TOKEN)
    query = gdata.contacts.client.ContactsQuery()
    query.max_results = 200
    query.start_index = 1
    return get_feeds(client.GetContacts(q=query))

#    update_items()
#    {"name": "Yaron Eisenstein", "id": "1414483744"}
#    request.graph['1414483744'].feed.post(
#        message='message with notify as I saw'
#    )
#    request.graph.me.feed.post(
#        message='message to the wall',
#        to = '{"name": "Yaron Eisenstein", "id": "1414483744"}'
#    )
